#include <ioLib.h>
#include <stdio.h>
#include <string.h>
#include <taskLib.h>
#include "tJournal.h"

/* Add a log entry in posting into the FIFO a new structure */
void add_log( LOG_TYPE type, const char* task, const char* msg )
{
	LOG_ENTRY log;
	
	log.type = type;
	log.time = time(NULL);
	strcpy( log.task, task );
	strcpy( log.msg, msg );
	
	msgQSend( msg_log, (char*) &log, sizeof(log), WAIT_FOREVER, 0 );
}

/*
* The tJournal task routine
*/
void tJournal()
{
	int fd;
	char buffer[512];
	char mustStop;
	    
	/* First open the file */
	fd = open( LOG_FILE , O_CREAT | O_RDWR , 644 );
	if( fd <= 0 )
	{
		perror( "Cannot open log file !\n" );
		exit( 0 );
	}
	
	lseek( fd, 0, SEEK_END );
	
	/* Put a delimitor in the file */
	sprintf( buffer , "------------------------------------------------------%s", END_OF_LINE );
	write( fd, buffer , strlen( buffer) );
	  
	/* Then, create the FIFO that will receive pending log structs */
	msg_log = msgQCreate( MAX_LOG_ENTRIES, sizeof(LOG_ENTRY), MSG_Q_FIFO );
	if( msg_log == NULL )
	{
		perror( "Cannot initialize log queue !\n" );
		exit( 0 );
	}
 
	/* Task body */
	mustStop = 0;
	while( mustStop == 0 )
	{
		LOG_ENTRY msgRecu;
		char type[32];
		
		/* Wait until there is a log entry to handle */
		msgQReceive( msg_log, (char*) &msgRecu, sizeof(msgRecu), WAIT_FOREVER );
		
        /* Look at the message type */			
		switch( msgRecu.type )
		{		
			case LOG_TYPE_NORMAL:
				sprintf( type, "INFO" );
				break;
			case LOG_TYPE_WARNING:
				sprintf( type, "WARNING" );
				break;
			case LOG_TYPE_ERROR:
				sprintf( type , "ERROR" );
				break;
		}
		
		/* If the message is the stop message, insert a special line */
		if( msgRecu.type == LOG_TYPE_STOP )
		{
			time_t t;
			char* hour;
			
			t = time(NULL);
			hour = ctime( &t );
			
			sprintf( buffer, "INFO, %s, ALL, Application stops now.%s", hour, END_OF_LINE );
			
			mustStop = 1;
		}
		else
		{
			char* hour = ctime( &msgRecu.time );
			sprintf( buffer, "%s, %s, %s, %s%s", type, hour, msgRecu.task, msgRecu.msg, END_OF_LINE );
		}
		
		write( fd, buffer, strlen( buffer ) );
	}

	/* Finally, release queue and file */
	msgQDelete( msg_log );
	
	close( fd );
	
	exit( 0 );
}

